package com.smartstate.ems.controller;

import com.alibaba.fastjson.JSON;

import com.smartstate.ems.core.BaseController;
import com.smartstate.ems.service.MyAuthenticationService;
import com.smartstate.ems.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/home")
@Api(tags = "auth")
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class HomeController extends BaseController {
    @Resource
    private TokenStore tokenStore;
    @Resource
    private MyAuthenticationService myAuthenticationService;
    @Resource
    private DiscoveryClient discoveryClient;
    /**
     * 查询用户在此接口下有没有权限
     * @return
     */
    @GetMapping("/authentication")
    public ResultVO<Object> authentication(@RequestParam("api") String api, @RequestParam String referer, @RequestParam String method) {
        return ResultVO.ok(myAuthenticationService.authentication(api,referer,method));
    }

    @GetMapping("/principal")
    @ApiOperation(value = "获取当前用户信息Principal")
    public ResultVO user(Principal member) {
        String s = JSON.toJSONString(member);
        Map map = JSON.parseObject(s, Map.class);
        return ResultVO.ok(map.get("principal"));
    }


    /**
     * 清除token（注销登录）
     */
//    @SysLog("登出")
    @DeleteMapping("/logout")
    @ApiOperation(value = "登出")
    public ResultVO ogout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
        if (StringUtils.isBlank(authHeader)) {
            return ResultVO.fail("退出失败，token 为空");
        }
        String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StringUtils.EMPTY).trim();
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
        tokenStore.removeAccessToken(accessToken);
        OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
        tokenStore.removeRefreshToken(refreshToken);
        return ResultVO.ok("注销成功");
    }

    @GetMapping("/serviceurl")
    public ResultVO<Map<String, List<ServiceInstance>>> serviceUrl() {
        Map<String, List<ServiceInstance>> msl = new HashMap<>();
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            List<ServiceInstance> sis = discoveryClient.getInstances(service);
            msl.put(service, sis);
        }
        return ResultVO.ok(msl);
    }

}
